/*
 * TimeRectifier.cpp
 *
 *  Created on: 2016年10月10日
 *      Author: zhengboyuan
 */

#include "TimeRectifier.h"

namespace util
{

TimeRectifier::TimeRectifier():
		m_deviation(5),
		m_count(),
		m_start(),
		m_last(),
		m_offset(),
		m_avgDuration(1)
{
}

TimeRectifier::~TimeRectifier()
{
}

int64_t	TimeRectifier::rectify(int64_t ts)
{
	m_count ++;

	if (m_count <= 1)
	{
		m_start = ts;
		m_last = ts;

		return ts;
	}

	if (ts > m_last)
	{
		int64_t duration = (ts - m_last);

		if (m_avgDuration <= 0)
		{
			m_avgDuration = duration;
		}
		else
		{
			m_avgDuration = (m_avgDuration * m_count + duration) / (m_count+1);
		}

		if (duration >= (m_avgDuration * m_deviation))
		{
			m_offset += duration - m_avgDuration;
		}

	}
	else if (ts < m_last)
	{
		int64_t duration = (m_last - ts);
		m_offset -= duration + m_avgDuration;
	}
	else
	{
		m_offset -= m_avgDuration;
	}

	int64_t timestamp = (ts - m_offset);
	m_last = ts;

	return timestamp;
}

void TimeRectifier::setDeviation(int dev)
{
	if (dev > 0)
	{
		m_deviation = dev;
	}
}

int64_t TimeRectifier::getStart() const
{
	return m_start;
}

int64_t TimeRectifier::getAvgDuration() const
{
	return m_avgDuration;
}

void TimeRectifier::reset()
{
	m_count = 0;
	m_avgDuration = 1;
	m_start = 0;
	m_offset = 0;
	m_last = 0;
}


} /* namespace util */
